package BT;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 曹见朋
 * @create 2024-06-24-21:54
 */
public class Main113 {

    // TODO 113. 路径总和 II
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> paths = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        getPath(root, path, paths, targetSum);
        return paths;
    }

    public static void getPath(TreeNode root, List<Integer> path, List<List<Integer>> paths, int targetSum){
        if(root == null) return;
        path.add(root.val);
        if(root.left == null && root.right == null){
            int sum = 0;
            Iterator<Integer> iterator = path.iterator();
            while(iterator.hasNext()){
                sum += iterator.next();
                System.out.println(sum);
            }
            if(sum == targetSum){
                paths.add(new ArrayList<Integer>(path));
            }
        }
        getPath(root.left, path, paths, targetSum);
        getPath(root.right, path, paths, targetSum);
        path.remove(path.size() - 1);
    }

}

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
